package com.itheima.canal.listener;


import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@CanalEventListener //声明当前的类是canal的监听类
public class BusinessListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * @param entryType 数据库的类型
     * @param rowData   数据库的数据
     */

    @ListenPoint(schema = "changgou_business", table = "tb_ad")
    public void adUpdate(CanalEntry.EntryType entryType, CanalEntry.RowData rowData) {
        System.out.println("广告表数据发生改变");

        /*rowData.getBeforeColumnsList().forEach((column -> {
            System.out.println("改变之前：" + column.getName() + "::" + column.getValue());
        }));

        rowData.getAfterColumnsList().forEach((column) -> {
            System.out.println("改变之后：" + column.getName() + "::" + column.getValue());
        });*/

        /**
         * column: 列
         */
        /*List<CanalEntry.Column> beforeColumnsList = rowData.getBeforeColumnsList();
        for (CanalEntry.Column column : beforeColumnsList) {
            String columnName = column.getName();
            String columnValue = column.getValue();
            System.out.println("改变之前：" + columnName + "::" + columnValue);
        }*/

        /*List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
        for (CanalEntry.Column column : afterColumnsList) {
            String columnName = column.getName();
            String columnValue = column.getValue();
            System.out.println("改变之后：" + columnName + "::" + columnValue);
        }*/

        List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
        for (CanalEntry.Column column : afterColumnsList) {
            //判断数据库字段是不是position（位置）
            if ("position".equals(column.getName())) {
                System.out.println("发送最新的数据到MQ:" + column.getValue());

                rabbitTemplate.convertAndSend("", RabbitMQConfig.AD_UPDATE_QUEUE, column.getValue());
            }
        }

    }
}
